package edu.uoc.tdp.pac4.client.logandreg;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.rmi.RemoteException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.TitledBorder;
import edu.uoc.tdp.pac4.beans.Attendance;
import edu.uoc.tdp.pac4.beans.Group;
import edu.uoc.tdp.pac4.beans.Shift;
import edu.uoc.tdp.pac4.client.ClientConnectionHelper;
import edu.uoc.tdp.pac4.common.AcademicManagementInterface;
import edu.uoc.tdp.pac4.common.util.LanguageUtils;

/**
 * JPanel to show the options relative to groups management
 * @author Laia
 *
 */
/**
 * @author Laia
 * 
 */
public class Attendance_StartAttendance extends JPanel {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;


	private JComboBox<String> comboBox;
	private JLabel lblInfo;
	private JButton btnStop;
	private JButton btnBegin;
	private JLabel lblCount;

	ClientConnectionHelper connectionHelper_ = null;
	AcademicManagementInterface academicManagement;


	/**
	 * Builds the JPanel
	 */

	public Attendance_StartAttendance(ClientConnectionHelper connectionHelper) {
		connectionHelper_ = connectionHelper;
		academicManagement = connectionHelper_.getAcademicManager();
		
		String nom = ClientConnectionHelper.getLoggedUser().getNombre() + " "
				+ ClientConnectionHelper.getLoggedUser().getApellidos();
		String profId = ClientConnectionHelper.getLoggedUser().getNIF();

		setBorder(new TitledBorder(
				null,
				LanguageUtils
						.getMessage("client.management.button.titleStartAttendance"),
				TitledBorder.LEADING, TitledBorder.TOP, null, null));
		setLayout(null);

		JPanel panel = new JPanel();
		panel.setBounds(6, 16, 619, 333);
		add(panel);
		panel.setLayout(null);

		JLabel lblNomDelCurs = new JLabel(
				LanguageUtils.getMessage("client.management.button.group"));
		lblNomDelCurs.setBounds(24, 157, 134, 14);
		panel.add(lblNomDelCurs);

		comboBox = new JComboBox<String>();
		comboBox.setBounds(170, 154, 220, 20);
		try {
			comboBox.setModel(posarModel(profId));
		} catch (RemoteException e1) {
			e1.printStackTrace();
		}
		panel.add(comboBox);

		btnBegin = new JButton(
				LanguageUtils.getMessage("client.management.button.begin"));
		btnBegin.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				try {
					beginAttendance();
				} catch (RemoteException e) {
					e.printStackTrace();
				}
			}
		});
		btnBegin.setBounds(24, 208, 163, 23);
		panel.add(btnBegin);

		btnStop = new JButton(
				LanguageUtils.getMessage("client.management.button.stop"));
		panel.add(btnStop);
		btnStop.setEnabled(false);

		btnStop.setBounds(257, 208, 132, 23);

		JLabel lblProf = new JLabel(
				LanguageUtils.getMessage("client.management.button.teacher"));
		lblProf.setBounds(24, 71, 95, 14);
		panel.add(lblProf);

		JLabel lblDate = new JLabel(
				LanguageUtils.getMessage("client.management.button.date"));
		lblDate.setBounds(24, 115, 105, 14);
		panel.add(lblDate);


		JLabel lblNewLabel_1 = new JLabel(nom);
		lblNewLabel_1.setBounds(170, 71, 106, 14);
		panel.add(lblNewLabel_1);

		Date dNow = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yy");

		JLabel lblNewLabel_2 = new JLabel(dateFormat.format(dNow));
		lblNewLabel_2.setBounds(170, 115, 76, 14);
		panel.add(lblNewLabel_2);

		lblInfo = new JLabel();
		lblInfo.setBounds(24, 259, 434, 20);
		panel.add(lblInfo);

		lblCount = new JLabel();
		lblCount.setBounds(24, 300, 346, 14);
		panel.add(lblCount);

	}

	/**
	 * Begin attendance
	 * 
	 * @throws RemoteException
	 */
	public void beginAttendance() throws RemoteException {

		String error = LanguageUtils.getMessage("client.management.error");

		String nameGroup = (String) comboBox.getSelectedItem();
		String delims = "[.]";
		String[] tokens = null;
		try {
			tokens = nameGroup.split(delims);
		} catch (NullPointerException e) {
			warn(LanguageUtils.getMessage("client.management.error.selecgrup"),
					error);
			return;
		}

		String name = tokens[0];
		String shiftString = tokens[1];

		Shift shift = null;
		if (shiftString.equals(Shift.MORNING.toString())) {
			shift = Shift.MORNING;
		} else {
			shift = Shift.AFTERNOON;
		}

		final Group group = academicManagement.findGroupByNameAndShift(name,
				shift);

		final Attendance attendance = academicManagement.saveAttendance(group);
		java.util.Date today = new java.util.Date();

		boolean dataOk = false;
		if (today.after(group.getStartDate())
				&& today.before(group.getFinalDate())) {
			dataOk = true;
		}
		if (!dataOk) {
			warn(LanguageUtils.getMessage("client.management.error.notActive"),
					error);
		} else {

			lblInfo.setText(LanguageUtils
					.getMessage("client.management.error.startAttendance")
					+ " " + name + " " + shift.toString());
			btnStop.setEnabled(true);
			btnBegin.setEnabled(false);
			
			
			//stops attendance and counts present and missing students
			btnStop.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {

					try {
						academicManagement.closeAttendance(attendance);
						btnStop.setEnabled(false);
						btnBegin.setEnabled(true);

						int total = academicManagement.countTotal(attendance.getGroupid());
						int presents = academicManagement
								.countPresents(attendance);
						int absents = total - presents;
						lblCount.setText(LanguageUtils
								.getMessage("client.management.error.count1")
								+ " "
								+ presents
								+ " "
								+ LanguageUtils
										.getMessage("client.management.error.count2")
								+ " "
								+ absents
								+ " "
								+ LanguageUtils
										.getMessage("client.management.error.count3"));
						academicManagement.updateAttendance(presents, absents,
								attendance);

					} catch (RemoteException e) {
						e.printStackTrace();
					}

				}
			});
		}
	}

	/**
	 * Populates the comboBoxModel with names of courses.
	 * 
	 * @param profId
	 * 
	 * @return
	 * @throws RemoteException
	 */
	public DefaultComboBoxModel<String> posarModel(String profId)
			throws RemoteException {
		List<Group> groups;
		groups = academicManagement.listGroupsByProf(profId);
		DefaultComboBoxModel<String> model = new DefaultComboBoxModel<String>();
		model.addElement(null);
		for (int i = 0; i < groups.size(); i++) {
			model.addElement(groups.get(i).getName() + "."
					+ groups.get(i).getShift());
		}
		return model;

	}

	public void warn(String main, String sec) {
		JOptionPane.showMessageDialog(null, main, sec,
				JOptionPane.ERROR_MESSAGE);
	}
}
